package config

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
)

func LoadDBConfig(dbConfigPath string, fileName string) (*DBConfig, error) {
	if dbConfigPath == "" {
		return nil, fmt.Errorf("dbConfigPath is empty")
	}
	if fileName == "" {
		return nil, fmt.Errorf("fileName is empty")
	}
	// 构建完整文件路径
	fullPath := filepath.Join(dbConfigPath, fileName)

	// 检查文件是否存在
	if _, err := os.Stat(fullPath); os.IsNotExist(err) {
		return nil, fmt.Errorf("db config file does not exist: %s", fullPath)
	}

	// 读取文件内容
	data, err := os.ReadFile(fullPath)
	if err != nil {
		return nil, fmt.Errorf("failed to read db config file '%s': %w", fullPath, err)
	}

	// 如果文件为空，返回错误
	if len(data) == 0 {
		return nil, fmt.Errorf("db config file is empty: %s", fullPath)
	}

	// 解析JSON
	dbConfig := &DBConfig{}
	err = json.Unmarshal(data, dbConfig)
	if err != nil {
		return nil, fmt.Errorf("failed to parse db config JSON from '%s': %w", fullPath, err)
	}

	// 验证配置
	if err := validateDBConfig(dbConfig); err != nil {
		return nil, fmt.Errorf("invalid db config in '%s': %w", fullPath, err)
	}
	return dbConfig, nil
}

// validateDBConfig 验证数据库配置的有效性
func validateDBConfig(dbConfig *DBConfig) error {
	if dbConfig == nil {
		return fmt.Errorf("dbConfig is nil")
	}

	if len(dbConfig.Clients) == 0 {
		return fmt.Errorf("no clients defined in db config")
	}

	// 检查客户端配置
	clientNames := make(map[string]bool)
	for i, client := range dbConfig.Clients {
		// 检查客户端名称
		if client.Name == "" {
			return fmt.Errorf("client [%d] has empty name", i)
		}

		// 检查客户端名称是否重复
		if clientNames[client.Name] {
			return fmt.Errorf("duplicate client name: %s", client.Name)
		}
		clientNames[client.Name] = true

		// 检查DNS配置
		if len(client.DNS) == 0 {
			return fmt.Errorf("client [%s] has no DNS configured", client.Name)
		}

		// 验证DNS格式（简单验证）
		for j, dns := range client.DNS {
			if dns == "" {
				return fmt.Errorf("client [%s] has empty DNS at index %d", client.Name, j)
			}
		}
	}

	// 检查必需的客户端是否存在
	requiredClients := []string{"model_db", "rpc_server_db"}
	for _, requiredClient := range requiredClients {
		if !hasClient(dbConfig.Clients, requiredClient) {
			return fmt.Errorf("required client '%s' not found", requiredClient)
		}
	}

	return nil
}

// hasClient 检查是否存在指定名称的客户端
func hasClient(clients []Client, clientName string) bool {
	for _, client := range clients {
		if client.Name == clientName {
			return true
		}
	}
	return false
}
